<?php

namespace app\common\model\order;

use app\common\model\Cart;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\shop\SkuProduct;
use app\common\model\User;
use app\common\model\user\Address;
use think\Db;
use think\Model;


class Order extends Model
{





    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_type_text',
        'createtime_text',
        'paytime_text',
        'order_status_text',
        'sendtime_text',
        'taketime_text',
    ];



    public function getPayTypeList()
    {
        return ['1' => __('Pay_type 1'), '2' => __('Pay_type 2'), '3' => __('Pay_type 3'), '4' => __('Pay_type 4'), '5' => __('Pay_type 5')];
    }

    public function getOrderStatusList()
    {
        return ['0' => __('Order_status 0'), '10' => __('Order_status 10'), '20' => __('Order_status 20'), '30' => __('Order_status 30'), '40' => __('Order_status 40')];
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getTaketimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['taketime']) ? $data['taketime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getOrderStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_status']) ? $data['order_status'] : '');
        $list = $this->getOrderStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getSendtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['sendtime']) ? $data['sendtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setSendtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function ordergoods()
    {
        return $this->hasMany(Goods::class, 'order_id', 'id');
    }
    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    static function yuOrder($cart_ids, $uid, $address_id = 0)
    {
        $userInfo = User::get($uid);
        $integral_proportion = config('site.integral_proportion');
        $goodsList = collection(Cart::with(['product', 'goods'])->whereIn('cart.id', $cart_ids)->select())->toArray();

        $total_points = $total_fee = $vip_price = $discount_price = $pay_fee = 0;
        foreach ($goodsList as &$v) {

            // SkuProduct::checkGoods($v);
            $goods = $v['goods'];
            $product = $v['product'];
            $total_fee += bcmul($product['price'], $v['num'], 2);
            $vip_price += bcmul($product['vip_price'], $v['num'], 2);
            $discount_price += bcmul($product['discount_price'], $v['num'], 2);

            if (in_array($goods['type'], ['1', '2'])) {
                $pay_price= bcmul($product['price'], $v['num'], 2);
            }
            if ($goods['type'] == 3) {
                $pay_price= bcmul($product['discount_price'], $v['num'], 2);
            }
            if ($goods['type'] == 4) {
                if ($userInfo->level > 0) {
                    $pay_price = bcmul($product['vip_price'], $v['num'], 2);
                } else {
                    $pay_price = bcmul($product['price'], $v['num'], 2);
                }
            }
            if ($integral_proportion > 0) {
                $v['points'] = bcmul($pay_price, $integral_proportion, 0);
            }
            $v['pay_fee'] = $pay_price;
            $pay_fee +=  $v['pay_fee'];
            $total_points +=  $v['points'];
        }
        //地址信息
        if (isset($address_id) && !empty($address_id)) {
            $addressInfo = Address::get([$address_id]);
            $data['addressInfo'] = $addressInfo;
            $data['address_id']  = $address_id;
        } else {
            $addressInfo = Address::getDefaultAddress($uid);
            if ($addressInfo) {
                $data['addressInfo'] = $addressInfo;
                $data['address_id']  = $addressInfo['id'];
            }
        }
        $discount_fee = bcsub($total_fee, $pay_fee, 2);
        $data['goodsList'] = $goodsList;
        $data['total_num'] = array_sum(array_column($goodsList, 'num'));
        $data['total_fee'] = $total_fee;
        $data['total_points'] = $total_points;
        $data['pay_fee'] = $pay_fee;
        $data['discount_fee'] = $discount_fee;
        $data['user_id'] = $uid;
        $data['cart_ids'] = $cart_ids;
        return $data;
    }

    static function addOrder($param)
    {
        extract($param);
        Db::startTrans();
        try {
            if (!isset($address_id) || !$address_id) {
                exception('收货地址错误');
            }
            if (!isset($total_num) || $total_num <= 0) {
                exception('购买数量错误');
            }
            $order = [
                'user_id' => $user_id,
                'sn' => sn('order', 'sn', 'NO'),
                'total_num' => $total_num,
                'total_fee' => $total_fee,
                'total_points' => $total_points,
                'address_id' => $address_id,
                'contact' => $addressInfo['contact'] ?? '',
                'telephone' => $addressInfo['telephone'] ?? '',
                'address' => $addressInfo['province'] . $addressInfo['city'] . $addressInfo['area']  . $addressInfo['address'],
                'discount_fee' => $discount_fee,
                'pay_fee' => $pay_fee,
            ];
            $res = Order::create($order);
            foreach ($goodsList as $v) {
                SkuProduct::checkGoods($v);
                $product = SkuProduct::get($v['product_id']);
                $total_price =  bcmul($v['pay_fee'], $v['num'], 2);
                $data = [
                    'order_id' => $res->id,
                    'goods_id' => $v['goods_id'],
                    'product_id' => $v['product_id'],
                    'goods_num' => $v['num'],
                    'goods_name' => $v['goods']['name'],
                    'goods_type' => $v['goods']['type'],
                    'goods_price' => $v['product']['price'],
                    'total_price' => $total_price,
                    'image' => $v['goods']['image'],
                    'discount_fee' => bcsub($total_price, $v['pay_fee'], 2),
                    'pay_fee' => $v['pay_fee'],
                    'points' => $v['points'] ?? 0,
                    'spec_info' => json_encode($product),
                ];
                Goods::create($data);
                SkuProduct::reduceInventory($v['goods_id'], $v['product_id'], $v['num']);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return $res->id;
    }

    static function pay_completion($order_sn, $transaction_id = '')
    {
        $order = Order::get(['sn' => $order_sn, 'order_status' => '0']);
        if ($order) {
            $order->order_status = '10';
            $order->paytime = time();
            $order->transaction_id = $transaction_id;
            $order->save();
            $userinfo = User::get($order->user_id);
            if ($order->total_points > 0 && $userinfo->level > 0) {
                ScoreLog::income($order->user_id,  $order->total_points, 1, 101, $order->sn);
            }
            MoneyLog::subcommission($order->user_id, $order->sn);
        }
    }
}
